package com.example.orchid.paper.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.View;

/**
 * BaseFragment
 * Created by Orchid on 2015-10-12.
 */
public abstract class BaseFragment extends Fragment {
    private Bundle savedState;

    public BaseFragment() {
        super();
        if (getArguments() == null) {
            setArguments(new Bundle());
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!restoreStateFromArguments()) {
            onFirstTimeLaunched();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        saveStateToArguments();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveStateToArguments();
    }

    private void saveStateToArguments() {
        if (getView() != null) {
            savedState = savedState();
        }
        if (savedState != null) {
            Bundle b = getArguments();
            b.putBundle("internalSavedViewState", savedState);
        }
    }

    private boolean restoreStateFromArguments() {
        Bundle b = getArguments();
        savedState = b.getBundle("internalSavedViewState");
        if (savedState != null) {
            restoreState();
            return true;
        }
        return false;
    }

    private void restoreState() {
        if (savedState != null) {
            onRestoreState(savedState);
        }
    }

    private Bundle savedState() {
        Bundle state = new Bundle();
        onSaveState(state);
        return state;
    }

    protected abstract void onRestoreState(Bundle savedInstanceState);

    protected abstract void onSaveState(Bundle outState);

    protected abstract void onFirstTimeLaunched();
}
